package com.tim.javaApi.concurrent;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ThreadDemo {

	private static final Logger log = LoggerFactory.getLogger(ThreadDemo.class);

	
	public void interrupt1() throws InterruptedException {
		Thread thread=new Thread(()->{
			int i=0;
			while(!Thread.currentThread().isInterrupted()){
				i++;
			}
			System.out.println("ThreadTest interrupt1:"+i);
		},"interruptDemo");
		thread.start();
		TimeUnit.SECONDS.sleep(1);
		thread.interrupt();
		System.out.println(thread.isInterrupted());
		new CountDownLatch(1).await();
	}
	
	public void interrupt2() throws InterruptedException {
		Thread thread=new Thread(()->{
			while(!Thread.currentThread().isInterrupted()){
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
//                    e.printStackTrace();
					System.out.println("thread isInterrupted1:"+Thread.currentThread().isInterrupted());
					Thread.currentThread().interrupt(); //再次中断
					System.out.println("thread isInterrupted2:"+Thread.currentThread().isInterrupted());

				}
			}
		},"interruptDemo");
		thread.start();
		TimeUnit.SECONDS.sleep(1);
		thread.interrupt();
		System.out.println(thread.isInterrupted());
	}

	
	public void extendThreadLocal() {
		ThreadLocal<String> tl = new ThreadLocal<String>(){
			@Override
			protected String initialValue() {
				return UUID.randomUUID().toString();
			}
		};
		for (int i = 0; i < 10; i++) {
			System.out.println(tl.get());
		}
		tl.set("nana");
		log.info(tl.get());

	}

	
	public void threadInterrupt() throws InterruptedException{
		Thread t = new Thread(){
			@Override
			public void run() {
				System.out.println("t1 run start ");
				for (int i = 0; i < Long.MAX_VALUE; i++) {

				}
				System.out.println("t1 run end ");
			}
		};
		interruptThread(t, "new");
		t.start();
		interruptThread(t, "start");
		t.yield();
		interruptThread(t, "yield");

		t = new Thread(){
			@Override
			public void run() {
				System.out.println("t2 run start ");
				try {
					Thread.sleep(12345);// Thread.currentThread()睡眠，非调用对象睡眠
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("t2 run end ");
			}
		};
		t.start();
		interruptThread(t, "sleep");

	}

	private void interruptThread(Thread t, String status){
		try {
			System.out.println(String.format("%s, interrupt=%s", status, t.isInterrupted()));
			t.interrupt();
			System.out.println(String.format("%s, ok, interrupt=%s", status, t.isInterrupted()));
		}catch (Exception e){
			System.out.println(status);
			e.printStackTrace();
		}
	}
}
